package com.xyhuo.leetcode.december;

import java.util.*;

/**
 * 字母异位词分组
 * https://leetcode.cn/problems/group-anagrams/
 *
 * @time 2023/12/19
 */
public class GroupAnagrams {

//    public static void main(String[] args) {
//        GroupAnagrams ga = new GroupAnagrams();
//        String[] strs = {"bdddddddddd", "bbbbbbbbbbc"};
//        ga.groupAnagrams(strs);
//    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();

        for (String str : strs) {
            int[] groupArray = strGroup(str);
            String groupStr = array2string(groupArray);
            if (map.containsKey(groupStr)) {
                map.get(groupStr).add(str);
            } else {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(groupStr, list);
            }
        }

        List<List<String>> ans = new ArrayList<>();
        Set<Map.Entry<String, List<String>>> entries = map.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            List<String> value = entry.getValue();
            ans.add(value);
        }
        return ans;
    }

    private int[] strGroup(String str) {
        int[] ans = new int[26];
        char[] charArray = str.toCharArray();
        for (char item : charArray) {
            ans[item - 'a']++;
        }
        return ans;
    }


    private String array2string(int[] array) {
        StringBuilder sb = new StringBuilder(26);
        for (int item : array) {
            sb.append(item);
            sb.append("#");
        }
        return sb.toString();
    }
}
